<?php
/**
 * This is the template for generating CRUD search class of the specified model.
 */

use yii\helpers\StringHelper;


/* @var $this yii\web\View */
/* @var $generator yii\gii\generators\crud\Generator */

$modelClass = StringHelper::basename($generator->modelClass);
$searchModelClass = StringHelper::basename($generator->searchModelClass);
if ($modelClass === $searchModelClass) {
    $modelAlias = $modelClass . 'Model';
}
$rules = $generator->generateSearchRules();
$labels = $generator->generateSearchLabels();
$searchAttributes = $generator->getSearchAttributes();
$searchConditions = $generator->generateSearchConditions();

echo "<?php\n";
?>

namespace <?= StringHelper::dirname(ltrim($generator->searchModelClass, '\\')) ?>;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use <?= ltrim($generator->modelClass, '\\') . (isset($modelAlias) ? " as $modelAlias" : "") ?>;

/**
 * <?= $searchModelClass ?> represents the model behind the search form about `<?= $generator->modelClass ?>`.
 */
class <?= $searchModelClass ?> extends <?= isset($modelAlias) ? $modelAlias : $modelClass ?>

{
    public $created_at_start;
    public $created_at_end;

    /**
    * @inheritdoc
    */
    public function attributeLabels()
    {
      return array_merge(
        parent::attributeLabels(),
        [
        'created_at_start' => '开始时间',
        'created_at_end' => '结束时间',
        ]
      );
    }
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            <?= implode(",\n            ", $rules) ?>,
            [['created_at_start','created_at_end'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
    * @param array() $params
    * @param int $pageSize
    * @param int $f 0|1
    * @return ActiveDataProvider
    */
    public function search($params,$pageSize = 20,$f = 0)
    {
        $query = <?= isset($modelAlias) ? $modelAlias : $modelClass ?>::find($f);

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => &$query,
            'pagination' => ['pageSize'=>$pageSize],
            'sort'=>[
                'defaultOrder'=>[
                    'id'=> SORT_DESC,
                ],
            ],
        ]);

        $this->load($params);

        if (!$this->validate()) {
            return $dataProvider;
        }

        // grid filtering conditions
        <?= implode("\n        ", $searchConditions) ?>

        if(!empty($this->created_at_start) && !empty($this->created_at_end)){
          $query->andFilterWhere(['between', $this->a.'.created_at', strtotime($this->created_at_start),strtotime($this->created_at_end)]);
        }


        return $dataProvider;
    }
}
